import hashlib

from django.http import HttpRequest
from django.shortcuts import render, redirect


# Create your views here.
from Seller import models


def register(request: HttpRequest):
    if request.method== 'POST':
        username = request.POST.get('username')
        nickname = request.POST.get('nickname')
        password = request.POST.get('password')

        password = encrypt(password)

        models.Seller.objects.create(name=username,nickname=nickname,password=password)


        return redirect('/Seller/login')

    return render(request, 'seller/register.html')


def login(request:HttpRequest):
    error_msg=''
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        password = encrypt(password)

        result = models.Seller.objects.filter(name=username,password=password)

        if result:
            return  redirect('/Seller/index')
        else:
            error_msg='账户密码错误或不存在'

    return render(request, 'seller/login.html',{'error msg':error_msg})


def encrypt(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()
    return result


def index(request:HttpRequest):
    return render(request, "seller/index.html")